import {
  Body,
  Controller,
  Get,
  HttpException,
  HttpStatus,
  Inject,
  Post,
  Query,
} from '@nestjs/common';
import { UserService } from './user.service';
import { RegisterUserDto } from './dto/register-user.dto';
import { RedisService } from 'src/redis/redis.service';
import { EmailService } from 'src/email/email.service';
import { LoginUserDto } from './dto/login-user.dto';
import { RequireLogin, UserInfo } from 'src/custom.decorator';
import { UpdateUserPasswordDto } from './dto/update-password.dto';
import { UpdateUserDto } from './dto/udpate-user.dto';
import { ApiOperation } from '@nestjs/swagger';

@Controller('user')
export class UserController {
  @Inject(EmailService)
  private emailService: EmailService;

  @Inject(RedisService)
  private redisService: RedisService;
  constructor(private readonly userService: UserService) {}

  @ApiOperation({ summary: '用户注册' })
  @Post(`register`)
  async register(@Body() registerUser: RegisterUserDto) {
    return await this.userService.register(registerUser);
  }

  @Get(`register-captcha`)
  async captcha(@Query('address') address: string) {
    // 授权码：ASvz7AvCG7UDU4U6
    const code = Math.random().toString().slice(2, 8);
    await this.redisService.set(`captcha_${address}`, code);
    await this.emailService.sendMail({
      html: `<p>你的注册验证码是 ${code}</p>`,
      to: address,
      subject: '注册验证码',
    });
    return '发送成功';
  }

  @Post(`login`)
  async userLogin(@Body() loginUser: LoginUserDto) {
    console.log('loginUser', loginUser);
    return await this.userService.login(loginUser);
  }

  @Get(`info`)
  @RequireLogin()
  async info(@UserInfo(`userId`) userId: number) {
    return await this.userService.findUserDetailById(userId);
  }

  @Post(`update_password`)
  @RequireLogin()
  async updatePassword(
    @Body() passwordDto: UpdateUserPasswordDto,
    @UserInfo() userInfo: any,
  ) {
    // console.log(userInfo)
    return await this.userService.updatePassword(passwordDto, userInfo);
  }

  @Get(`update_password/captcha`)
  async updatePasswordCaptcha(@Query('address') address: string) {
    if (!address) {
      throw new HttpException(`邮箱不能为空`, HttpStatus.BAD_REQUEST);
    }

    const code = Math.random().toString().slice(2, 8);

    await this.redisService.set(
      `update_password_captcha_${address}`,
      code,
      5 * 60,
    );

    await this.emailService.sendMail({
      to: address,
      html: `<p>你的更改密码验证码是 ${code}</p>`,
      subject: '更改密码验证码',
    });
    return '验证码已发送';
  }

  @Post(`update`)
  @RequireLogin()
  async update(
    @UserInfo(`userId`) userId: number,
    @Body() updateUserDto: UpdateUserDto,
  ) {
    return await this.userService.update(userId, updateUserDto);
  }

  
}
